﻿using GrayParrot.Configuration;
using GrayParrot.RabbitMQ.Configuration;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GrayParrot.Scheduling;
using GrayParrot.Core.Serialization;

namespace GrayParrot.RabbitMQ
{
    [Serializable]
    [DisallowConcurrentExecution]
    public class ScheduledMessage<T> : MessageBusBase<T>, IJob where T : class, new()
    {
        private string m_subscriptionKey = string.Empty;
        private MessageBusBase<T> Value = default(MessageBusBase<T>);

        public string SubscriptionKey
        {
            get { return m_subscriptionKey; }
            set { m_subscriptionKey = value; }
        }

        public ScheduledMessage()
        {

        }

        public ScheduledMessage(string subscriptionKey)
        {
            m_subscriptionKey = subscriptionKey;
        }

        public void Execute(IJobExecutionContext context)
        {
            try
            {
                JobDataMap m_parameters = context.JobDetail.JobDataMap;
                if (m_parameters != null && m_parameters.ContainsKey("subscription"))
                {
                    m_subscriptionKey = m_parameters["subscription"].ToString();
                }

                if (m_parameters != null && m_parameters.ContainsKey(JobParameters.INSTANCE_NAME))
                {
                    MessageBusBase<T> m_value = m_parameters[JobParameters.INSTANCE_NAME].ToString().DeserializeAsXml<MessageBusBase<T>>();
                    this.Value = m_value;
                }

                if (m_subscriptionKey != string.Empty)
                {
                    SchedulerContext m_context = context.Scheduler.Context;

                    ConfigurationManagerHelper pp = new ConfigurationManagerHelper();
                    GrayParrot.RabbitMQ.Configuration.Subscription m_sub = pp.GetSubscription(m_subscriptionKey);

                    GrayParrot.RabbitMQ.Publisher<T> m_pub = new GrayParrot.RabbitMQ.Publisher<T>(m_sub);

                    //bool result = m_pub.Send(new GrayParrot.RabbitMQ.MessageBusBase<T>() { Body = this.Value });
                    bool result = m_pub.Send(this.Value);

                    GrayParrot.Logging.Logger.For<ScheduledMessage<T>>().DebugFormat("Send message return {0}", result);
                }
            }
            catch (Exception ex)
            {
                GrayParrot.Logging.Logger.For<ScheduledMessage<T>>().Error(ex);
            }
        }
    }
}
